package bookstudytest.socket;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

/**
 * @Auther: Lee
 * @Date: 2018/6/15 18:50
 * @Description:
 */
public class InternetAddressTest {
    public static void main(String[] args) throws IOException {
//        InetAddress localHost = InetAddress.getLocalHost();
//        String hostName = localHost.getHostName();
//        byte[] address = localHost.getAddress();
//        String hostAddress = localHost.getHostAddress();
//        System.out.println(hostName);//计算机名
//        System.out.println(address);//
//        System.out.println(hostAddress);//ip地址
        // 监听指定的端口
        int port = 55533;
        ServerSocket server = new ServerSocket(port);
        byte[] b = new byte[1024];
        // server将一直等待连接的到来
        System.out.println("server将一直等待连接的到来");
        String response = "大哥你好啊！";
        Socket socket = null;
        socket = server.accept();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        for (int i = 0; i < 5; i++) {
//            Charset charset = Charset.forName("utf-8");
            // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
            inputStream = socket.getInputStream();
            InputStreamReader is = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(is);
            BufferedInputStream bis = new BufferedInputStream(inputStream);
//            int read = bis.read();
//            int read1 = bis.read(b);
//            outputStream = socket.getOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                sb.append(new String(bytes, 0, len, "GBK"));
            }
//            outputStream.write(response.getBytes("GBK"));
            System.out.println("get message from client: " + sb);
        }
        inputStream.close();
        socket.close();
        server.close();

    }

    public static String repeatServer(ServerSocket server) throws IOException {
        return null;
    }
}
